import api from '../../api'

const state = {
  todayMood: null,
  recentMoods: [],
  moodStats: null
}

const mutations = {
  SET_TODAY_MOOD(state, mood) {
    state.todayMood = mood
  },
  SET_RECENT_MOODS(state, moods) {
    state.recentMoods = moods
  },
  SET_MOOD_STATS(state, stats) {
    state.moodStats = stats
  },
  ADD_MOOD(state, mood) {
    if (state.recentMoods.length > 0) {
      state.recentMoods = [mood, ...state.recentMoods]
    } else {
      state.recentMoods = [mood]
    }
    // 如果是今天的心情，更新todayMood
    const today = new Date().toISOString().split('T')[0]
    const moodDate = new Date(mood.recordDate).toISOString().split('T')[0]
    if (today === moodDate) {
      state.todayMood = mood
    }
  }
}

const actions = {
  // 获取今日心情
  async fetchTodayMood({ commit }) {
    try {
      const mood = await api.mood.getTodayMood()
      commit('SET_TODAY_MOOD', mood)
      return mood
    } catch (error) {
      commit('SET_TODAY_MOOD', null)
      throw error
    }
  },
  
  // 获取最近心情记录
  async fetchRecentMoods({ commit }) {
    try {
      const moods = await api.user.getRecentRecords()
      commit('SET_RECENT_MOODS', moods)
      return moods
    } catch (error) {
      throw error
    }
  },
  
  // 获取心情统计数据
  async fetchMoodStats({ commit }) {
    try {
      const stats = await api.mood.getMoodReport()
      commit('SET_MOOD_STATS', stats)
      return stats
    } catch (error) {
      throw error
    }
  },
  
  // 创建心情记录
  async createMoodRecord({ commit }, moodData) {
    try {
      const result = await api.mood.createMoodRecord(moodData)
      commit('ADD_MOOD', { ...moodData, id: result.id })
      return result
    } catch (error) {
      throw error
    }
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
} 